package cn.lyd.org.service.impl;

import cn.lyd.base.service.impl.BaseServiceImpl;
import cn.lyd.base.until.PageList;
import cn.lyd.org.domain.Department;
import cn.lyd.org.mapper.DepartmentMapper;
import cn.lyd.org.query.DepartmentQuery;
import cn.lyd.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {
        /*
        * 1.查询出所有的部门，放在map集合里
        * 2.遍历部门，选出没有parent_id的部门=父部门,放在部门树的集合里
        * 3.选出有parent_id的部门=子部门，找出它的父部门，把子部门放到父部门的children中
        * */
        //查询所有部门
        List<Department> all = departmentMapper.findAll();

//        System.out.println("所有部门");
//        System.out.println(all);

        //放到map集合里
        Map<Long, Department> map = new HashMap<>();
        for (Department department : all){
            map.put(department.getId(),department);
        }

        //部门树集合
        List<Department> deptTree = new ArrayList<>();
        //遍历部门
            for (Department department : all){
                //选出没有parent_id的部门=顶级部门,放在部门树的集合里
                if (department.getParent_id()==null){
                    deptTree.add(department);
//                    System.out.println("第一层部门");
//                    System.out.println(deptTree);
                }
                else {
                    //选出有parent_id的部门=子部门,找出它的父部门，
                    Long parent_id = department.getParent_id();
                    Department parentDepartment = map.get(parent_id);
                        // 把子部门放到父部门的children中
                        List<Department> children = parentDepartment.getChildren();
                        children.add(department);

                }
            }
        return deptTree;
    }
}
